/**    
 * 文件名：Ex7ContentDetectionColor.java    
 *    
 * 版本信息：    
 * 日期：2014年3月10日    
 * xyj 足下 xyj 2014     
 * 版权所有    
 *    
 */
package opencvtest.chapter04;

import static com.googlecode.javacv.cpp.opencv_highgui.CV_LOAD_IMAGE_COLOR;
import static com.googlecode.javacv.cpp.opencv_imgproc.cvNormalizeHist;
import static com.googlecode.javacv.cpp.opencv_imgproc.cvReleaseHist;
import static opencvtest.OpenCVUtils.drawOnImage;
import static opencvtest.OpenCVUtils.loadAndShowOrExit;
import static opencvtest.OpenCVUtils.show;
import static opencvtest.OpenCVUtils.toIplROI;

import java.awt.Color;
import java.awt.Rectangle;
import java.io.File;

import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_imgproc.CvHistogram;

/**
 * Uses histogram of region in an color image to create 'template', looks
 * through the whole image to detect pixels that are similar to that template.
 * Example for section
 * "Backprojecting a histogram to detect specific image content" in Chapter 4.
 */
public class Ex7ContentDetectionColor {

    public static void main(String[] args) {

        // Load image as a color
        IplImage colorImage = loadAndShowOrExit(new File("data/waves.jpg"), CV_LOAD_IMAGE_COLOR);

        // Reduce colors
        ColorHistogram.colorReduce(colorImage, 32);

        // Display image with marked ROI
        Rectangle rect = new Rectangle(0, 0, 165, 75);
        show(drawOnImage(colorImage, rect, Color.RED), "Input");

        // Define ROI for sample histogram
        colorImage.roi(toIplROI(rect));

        // Compute histogram within the ROI
        CvHistogram hist = new ColorHistogram().getHistogram(colorImage);

        // Normalize histogram so the sum of all bins is equal to 1.
        cvNormalizeHist(hist, 1);

        // Remove ROI, we will be using full image for the rest
        colorImage.roi(null);

        // Prepare finder
        ContentFinder finder = new ContentFinder();
        finder.histogram = hist;
        finder.threshold = 0.05f;

        // Get back-projection of the color histogram
        IplImage result = finder.find(colorImage);
        cvReleaseHist(hist);

        // Show results
        show(result, "Backprojection result. White means match, black no match.");

    }

}
